package fr.bludwarf.skywarrior.utils;

import java.util.Calendar;

public class TimeUtils {
	
	public static String pad2(final int i)
    {
        if (i < 10)
        {
            return "0" + i;
        }
        else
        {
            return Integer.toString(i);
        }
    }
	
	private static Calendar newTime()
	{
		final Calendar date = Calendar.getInstance();
		date.set(Calendar.HOUR, 0);
		date.set(Calendar.HOUR_OF_DAY, 0);
		date.set(Calendar.MINUTE, 0);
		date.set(Calendar.SECOND, 0);
		date.set(Calendar.MILLISECOND, 0);
		return date;
	}
	
	public static String timeToString(final double seconds)
	{
		final Calendar date0 = newTime();
		final Calendar date = newTime();
		
		// Nombre de secondes
		date.set(Calendar.SECOND, (int) Math.round(seconds));
		
		// Nombre de jours
		final double diff = date.getTimeInMillis() - date0.getTimeInMillis();
		final int nbJours = (int) (diff / (24 * 3600 * 1000));
		
		return timeToString(nbJours, date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE), date.get(Calendar.SECOND));
	}
	
	private static String timeToString(final int nbJours, final int hours, final int mins, final int sec)
	{
		final StringBuilder sb = new StringBuilder();
		
		if (nbJours > 0)
		{
			sb.append(nbJours).append("j ");
		}
		if (hours > 0)
		{
			sb.append(hours).append("h ");
		}

		sb.append(pad2(mins)).append("m ").append(pad2(sec)).append("s");

		return sb.toString();
	}
}
